﻿var NodeID = UrlParm.parm('nodeid');
var ParmAc = UrlParm.parm('ac');
//这个方法要查询后台
var OptionsData = new Array(); //存储查询的数据
function getNextValue(id) {
    var _changeSel = $("#" + id);
    if (_changeSel.length == 0) return;
    var selName = _changeSel.attr("name");
    var _Step = Number(_changeSel.attr("step"));
    var _NextStep = _Step - 1;
    var valuetypeid = _changeSel.attr("valuetypeid");
    //当上结点改变时隐藏子结点
    for (var c = 1; c <= _NextStep; c++) {
        var _childID = selName + "_" + c.toString();
        var child = $("#" + _childID);
        if (child.length > 0) {
            child.hide();
        }
    }
    var _selVal = _changeSel.val();
    if (_selVal == "" || _selVal == "0") { return; }
    if (_NextStep > 0) {
        var _nextID = selName + "_" + _NextStep.toString();
        var _nextSel = $("#" + _nextID);
        if (_nextSel.length == 0) { //动态添加select
            var _strchange = 'onchange="getNextValue(this.id); "';
            if (_NextStep == 1) { _strchange = ''; }

            var _strSelect = '<select name="' + selName + '"  valuetypeid="' + valuetypeid + '"  step="' + _NextStep + '"  id="' + _nextID + '"  ' + _strchange + '></select>';
            _changeSel.parent().append(_strSelect); ;
            _nextSel = $("#" + _nextID); //再次获取下一个select;
        }
        _nextSel.hide();

        if (_selVal != null) {
            var items = null;
            for (var k in OptionsData) {   //读取当前存在的数据            
                if (OptionsData[k].id == _selVal) {
                    items = OptionsData[k];
                }
            }
            if (items == null) {  //向后台请求数据
                var returntext = $.ajax({ type: "POST", url: 'content_saveAdvance.aspx', data: 'ac=ajax_get_formvalue&tid=' + valuetypeid + '&id=' + _selVal, async: false }).responseText;
                var msg = eval("msg=" + returntext);
                if (msg.result == "1") { var _data = new Object(); _data.len = msg.len; _data.values = msg.items; ; _data.id = _selVal; OptionsData.push(_data); items = _data; }
                else {
                    // alert(msg.msg);出错信息
                }
            }
            if (items != null) {
                if (items.len != "0") {
                    _nextSel.empty();
                    for (var s in items.values) {
                        _nextSel.append('<option value="' + items.values[s].value + '">' + items.values[s].text + '</option>');
                    }
                    _nextSel.show();
                    _nextSel.change();
                }
            }
        }
    }
}
//表单验证
function check_formval() {
    var check_result = true;
    $(":input").each(function () {
        var o = $(this);
        if (o.attr("type") == "text") {
            //alert(o.attr('name'));
            if (o.attr("regstr") != null) {
                //alert(o.attr("regstr"));
                var reg = eval('/' + o.attr("regstr") + '/');
                //alert(reg.test(o.val())+"|"+o.attr('name')+"|"+o.val());
                if (!reg.test(o.val())) {
                    // alert($("#" + o.attr("name") + "_title").html() + o.attr("regtip"));
                    ShowError($("#" + o.attr("name") + "_title").html() + o.attr("regtip"));
                    CurrentObject = o;
                    check_result = false;

                }
            }
        }
    });
    if (check_result) {
        //parent.$('#msviLocalToolbar').hide();
        parent.ShowSysTip("正在保存信息……");
    }
    return check_result;
}

function tr_tab_showAndHiddeItem(sId, hId) {
    $("#" + sId).show();
    $("#" + sId + "_tab").css('background', '#2A7AD2 !important');
    $("#" + hId).hide();
    $("#" + hId + "_tab").css('background', '#999 !important');
}
//=========================相关文章Begin=============================
var LinksData = new Object(); //存放相关文章数据
LinksData.items = new Array();
LinksData.Add = function (flag, title, id) {//添加操作
    var FlagItem = new Object();
    var _flag_has = false;
    for (var i = 0; i < LinksData.items.length; i++) {
        if (LinksData.items[i].id == flag) {
            FlagItem = LinksData.items[i];
            _flag_has = true; break;
        }
    }
    if (!_flag_has) {
        FlagItem.id = flag;
        FlagItem.items = new Array();
        LinksData.items.push(FlagItem);
    }


    var item = new Object();
    item.id = id;
    item.title = title;
    var _has = false; //判断存在标识
    for (var i = 0; i < FlagItem.items.length; i++) {
        var _item = FlagItem.items[i];
        if (_item.id == id) {
            _has = true;
            break;
        }
    }

    if (!_has) {
        FlagItem.items.push(item);
        for (var i = 0; i < LinksData.items.length; i++) {
            if (LinksData.items[i].id == flag) {
                LinksData.items[i] = FlagItem;
                break;
            }
        }
    }
    return !_has;
}
LinksData.Remove = function (flag, id) { //移除选择的文章操作
    var FlagItem = new Object();
    var _flag_has = false;
    var _has = false;
    var _flag_index = -1;
    for (var i = 0; i < LinksData.items.length; i++) {
        if (LinksData.items[i].id == flag) {
            FlagItem = LinksData.items[i];
            _flag_index = i;
            _flag_has = true; break;
        }
    }

    if (_flag_has) {
        var index = -1;
        for (var i = 0; i < FlagItem.items.length; i++) {
            var _item = FlagItem.items[i];
            if (_item.id == id) {
                _has = true;
                index = i;
                break;
            }
        }

        if (_has) {
            RemoveArray(FlagItem.items, index);
            LinksData.items[_flag_index] = FlagItem;

        }
    }

}

LinksData.SetSelect = function (flag) {//重新设置Select
    var FlagItem = new Object();
    var _flag_has = false;
    for (var i = 0; i < LinksData.items.length; i++) {
        if (LinksData.items[i].id == flag) {
            FlagItem = LinksData.items[i];
            _flag_has = true; break;
        }
    }

    if (_flag_has) {
        var obj = $('#' + flag + '_Links');
        obj.empty();
        var val = '';
        for (var i = 0; i < FlagItem.items.length; i++) {
            var _item = FlagItem.items[i];
            obj.append('<option value="' + _item.id + '">' + _item.title + '</option>');
            if (val == '') {
                val = ',' + _item.id + ',';
            } else {
                val += _item.id + ',';
            }
        }
        $('#' + flag).val(val);
    }


}

LinksData.MoveUp = function (flag) {
    var obj = $('#' + flag + '_Links');
    var id = obj.val();
    var FlagItem = new Object();
    var _flag_has = false;
    var _has = false;
    var _flag_index = -1;
    var _item_index = -1;
    for (var i = 0; i < LinksData.items.length; i++) {
        if (LinksData.items[i].id == flag) {
            FlagItem = LinksData.items[i];
            _flag_index = i;
            _flag_has = true; break;
        }
    }
    if (_flag_has) {
        for (var i = 0; i < FlagItem.items.length; i++) {
            var _item = FlagItem.items[i];
            if (_item.id == id) {
                _has = true;
                _item_index = i;
                break;
            }
        }

        if (_item_index > 0) {
            var temp = FlagItem.items[_item_index - 1];
            FlagItem.items[_item_index - 1] = FlagItem.items[_item_index];
            FlagItem.items[_item_index] = temp;
            LinksData.items[_flag_index] = FlagItem;
        }
    }
}
LinksData.MoveDown = function (flag) {
    var obj = $('#' + flag + '_Links');
    var id = obj.val();
    var FlagItem = new Object();
    var _flag_has = false;
    var _has = false;
    var _flag_index = -1;
    var _item_index = -1;
    for (var i = 0; i < LinksData.items.length; i++) {
        if (LinksData.items[i].id == flag) {
            FlagItem = LinksData.items[i];
            _flag_index = i;
            _flag_has = true; break;
        }
    }
    if (_flag_has) {
        for (var i = 0; i < FlagItem.items.length; i++) {
            var _item = FlagItem.items[i];
            if (_item.id == id) {
                _has = true;
                _item_index = i;
                break;
            }
        }

        if (_item_index < FlagItem.items.length - 1) {
            var temp = FlagItem.items[_item_index + 1];
            FlagItem.items[_item_index + 1] = FlagItem.items[_item_index];
            FlagItem.items[_item_index] = temp;
            LinksData.items[_flag_index] = FlagItem;
        }
    }
}
//邦定相关文章
function bindLinksData(id) {
    var val = $("#" + id).val();
    if (val != '') {
        var returntext = $.ajax({ type: "POST", url: 'content_saveAdvance.aspx', data: 'ac=ajax_get_linksdata&id=' + val, async: false }).responseText;
        var msg = eval("msg=" + returntext);
        if (msg.result == "1") {
            var arrVal = val.split(',');
            for (var i = 0; i < arrVal.length; i++) {
                for (var s in msg.items) {
                    var item = msg.items[s];
                    if (arrVal[i] == item.id) {
                        LinksData.Add(id, item.title, item.id);
                    }
                }
            }
            LinksData.SetSelect(id);
        }
        else {
            alert(msg.msg); //出错信息
        }
    }
}
//查看选择的相关文章
function GoSelect_links(id) {
    alert("此功能尚未实现");
}
//添加相关文章
function editContentLink(id) {
    var leftPos = screen.availWidth / 2
    var topPos = screen.availHeight / 2
    var MyWIN = window.open("admin_editContentLink.aspx?nodeid=" + NodeID + '&setid=' + id, '', 'width=500,height=380,scrollbars=no,resizable=yes,titlebar=0,top=' + topPos + ',left=' + leftPos);

}
//添加关联可选值
function editUserDefinedLink(_typeid, _setid) {
    var leftPos = screen.availWidth / 2
    var topPos = screen.availHeight / 2
    show_dialog('editUserDefinedLink_list.aspx?typeid=' + _typeid + '&setid=' + _setid, 450, 230, '选择关联可选值');
}
function bindUserDefinedData(id) {
    var val = $("#" + id).val();
    if (val != '') {
        var returntext = $.ajax({ type: "POST", url: 'editUserDefinedLink_list.aspx', data: 'ac=ajax_get_linksdata&id=' + val, async: false }).responseText;
        var msg = eval("msg=" + returntext);
        if (msg.result == "1") {
            var arrVal = val.split(',');
            for (var i = 0; i < arrVal.length; i++) {
                for (var s in msg.items) {
                    var item = msg.items[s];
                    if (arrVal[i] == item.id) {
                        LinksData.Add(id, item.title, item.id);
                    }
                }
            }
            LinksData.SetSelect(id);
        }
        else {
            alert(msg.msg); //出错信息
        }
    }
}
//上移相关文章
function moveUp_links(id) {
    var obj = $('#' + id + '_Links');
    var selVal = obj.val();
    LinksData.MoveUp(id);
    LinksData.SetSelect(id);
    obj.val(selVal);

}
//下移相关文章
function moveDown_links(id) {
    var obj = $('#' + id + '_Links');
    var selVal = obj.val();
    LinksData.MoveDown(id);
    LinksData.SetSelect(id);
    obj.val(selVal);
}
//删除选择的相关文章
function del_links(id) {
    var obj = $('#' + id + '_Links');
    LinksData.Remove(id, obj.val());
    LinksData.SetSelect(id);
}

function add_links(id, param_index_id, param_title) {
    var obj = $('#' + id + '_Links');
    if (LinksData.Add(id, param_title, param_index_id)) {
        LinksData.SetSelect(id);
    }
    else {
        alert('你选择的文章已经存在了');
        obj.val(param_index_id);
    }

}
//移除数组元素
function RemoveArray(array, index) {
    // alert(index);
    var f = false;
    for (var i = 0, n = 0; i < array.length; i++) {
        if (i != index) {
            array[n++] = array[i]
        } else
            f = true;
    }
    if (f == true)
        array.length -= 1;
}


//=========================相关文章End=============================

$(document).ready(function () {

    $(".table_form tr:odd").css("background-color", "#FAFDFE");

    //alert(parent.window.location.href);
    try {
        if (parent.window.location.href.indexOf('admin_publish_eidt.aspx') > 0 && (ParmAc == '' || ParmAc == 'add' || ParmAc == 'edit')) {
            parent.$('#msviLocalToolbar').show();
        }
        parent.close_dialog();
    }
    catch (err) {

    }
    try {
        InitCookie();
    }
    catch (err) { }
    $(function () {
        if ($.browser.msie) {
            $('input:checkbox').click(function () {
                this.blur();
                this.focus();
            });
        };
        $("#chkPicLocating").change(function () {
            InitCookie();
        });
        /*
        $("#chkPicWater").change(function () {
        InitCookie();
        });
        */
        $("#chkPicWaterSelect").change(function () {
            InitCookie();
        });
        $("#chkPicResize").change(function () {
            InitCookie();
        });
        $("#txtWidth").change(function () {
            InitCookie();
        });
        $("#txtHeight").change(function () {
            InitCookie();
        });
    });
});

//========================= 编辑器相关的扩展方法  2011.08.18 李城编写 =============================
var EditorInstance;
var Currenttype;
//简繁转换
function ChangeSimplifie2TraditionalFont(data, InputID, controlID) {
    var _dataTraditionalFont = null;
    if ($("#" + InputID).val() == "简->繁") {
        $("#" + InputID).val("繁->简");
        _dataTraditionalFont = Simplifie2TraditionalFont(data);
    }
    else {
        $("#" + InputID).val("简->繁");
        _dataTraditionalFont = Traditional2SimplifieFont(data);
    }
    $('#' + controlID).val(_dataTraditionalFont);
    return _dataTraditionalFont;
}
//图片本地换选项
function InitCookie() {

    //是否本地化
    if ($("#chkPicLocating").attr("checked") == undefined) {
        $.cookie('chkPicLocating', false, { path: '/' });
    }
    else {
        $.cookie('chkPicLocating', true, { path: '/' });
    }

    //是否加水印
    if ($("#chkPicWaterSelect").val() == undefined || $("#chkPicWaterSelect").val() == "0") {
        $.cookie('chkPicWater', false, { path: '/' });
    }
    else {
        $.cookie('chkPicWater', true, { path: '/' });
    }
    //水印位置
    $.cookie('chkPicWaterSelect', $("#chkPicWaterSelect").val(), { path: '/' });

    //等比缩放选项
    if ($("#chkPicResize").attr("checked") == undefined) {
        $.cookie('chkPicResize', false, { path: '/' });
    }
    else {
        $.cookie('chkPicResize', true, { path: '/' });
    }
    $.cookie('PicResizeWidth', $("#txtWidth").val(), { path: '/' });
    $.cookie('PicResizeHeight', $("#txtHeight").val(), { path: '/' });

}
//保存水印图片至cookie中
function SaveCookieWaterPic(strWaterPic) {
    $.cookie('PicWaterImg', encodeURI(strWaterPic), { path: '/' });
}
//粘贴
function PasteForEditor() {
    switch (Currenttype) {
        case "xheditor":
            EditorInstance.exec("Paste");
            break;
        case "news_editor":
        case "ckeditor":
            CKEDITOR.tools.callFunction(24, this);
            break;
    }
    return false;
}
//格式化
function switchFormat(currentControlID) {
    switch (Currenttype) {
        case "xheditor":
            AdvanceFormatText(currentControlID, EditorInstance.getSource());
            break;
        case "news_editor":
        case "ckeditor":
            AdvanceFormatText(currentControlID, EditorInstance.getData());
            EditorInstance.setData($("#" + currentControlID).val());
            break;
        case "html_editor":
            var _html_editor = AdvanceFormatText(currentControlID, CodeMirroreditor.getValue());
            if (CodeMirroreditor) {
                CodeMirroreditor.setValue(_html_editor);
                CodeMirroreditor.refresh();
            }
            //editAreaLoader.setValue(currentControlID, $("#" + currentControlID).val());
            break;
    }
}
//图片自动分页
function PageAutoPage(currentControlID) {
    switch (Currenttype) {
        case "xheditor":
            PageAutoPageText(currentControlID, EditorInstance.getSource());
            break;
        case "news_editor":
        case "ckeditor":
            PageAutoPageText(currentControlID, EditorInstance.getData());
            EditorInstance.setData($("#" + currentControlID).val());
            break;
        case "html_editor":
            var _html_editor = PageAutoPageText(currentControlID, CodeMirroreditor.getValue());
            if (CodeMirroreditor) {
                CodeMirroreditor.setValue(_html_editor);
                CodeMirroreditor.refresh();
            }
            //editAreaLoader.setValue(currentControlID, $("#" + currentControlID).val());
            break;
    }
}
function SimpleAndTradiation(currentControlID) {
    switch (Currenttype) {
        case "xheditor":
            ChangeSimplifie2TraditionalFont(EditorInstance.getSource(), 'S2TControl', currentControlID);
            break;
        case "news_editor":
        case "ckeditor":
            ChangeSimplifie2TraditionalFont(EditorInstance.getData(), 'S2TControl', currentControlID);
            EditorInstance.setData($("#" + currentControlID).val());
            break;
        case "html_editor":
            if (CodeMirroreditor) {
                _html_editor = ChangeSimplifie2TraditionalFont(CodeMirroreditor.getValue(), 'S2TControl', currentControlID);
                CodeMirroreditor.setValue(_html_editor);
                CodeMirroreditor.refresh();
            }
            break;
    }
}
//初始化编辑器
var mixedMode = {
    name: "htmlmixed",
    scriptTypes: [{ matches: /\/x-handlebars-template|\/x-mustache/i,
        mode: null
    },
                      { matches: /(text|application)\/(x-)?vb(a|script)/i,
                          mode: "vbscript"
                      }]
};
CodeMirroreditor = null;
function InitEditor(controlID, type, strwidth, strheight, IsGetinitVal) {
    if (IsGetinitVal) {
        $("#" + controlID).val(unescape($("#" + controlID + "_hidden").val()));
    }
    strwidth = $(".content_editor").width() - 10;
    switch (type) {
        case "xheditor":
            EditorInstance = $("#" + controlID).xheditor({
                html5Upload: false,
                tools: 'Source,Cut,Copy,Paste,Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Anchor,Img,Flash,Media,Hr,Table,Preview,Print,Fullscreen',
                upMultiple: 10,
                width: strwidth,
                height: strheight,
                upImgUrl: "/js/xheditor/xheditor_plugins/upload.aspx",
                upImgExt: "jpg,jpeg,gif,png",
                upLinkUrl: "/js/xheditor/xheditor_plugins/uploadFile.aspx",
                upLinkExt: "zip,rar,txt,doc,docx,gz,gzip,ppt,pptx,rar,xls,xlsx"
            });
            break;
        case "news_editor":
        case "ckeditor":
            EditorInstance = CKEDITOR.replace(controlID, { width: strwidth, height: strheight });
            break;
        case "html_editor":
            CodeMirroreditor = CodeMirror.fromTextArea(document.getElementById(controlID), { mode: mixedMode, tabMode: "indent", lineNumbers: true });
            CodeMirroreditor.setSize(strwidth, strheight);
            CodeMirroreditor.refresh();
            //editAreaLoader.init({ id: controlID, start_highlight: true, allow_toggle: false, word_wrap: false, language: "zh", syntax: "html", allow_resize: "no" });
            break;
    }
}
//删除编辑器
function ReInstall(currentControlID, strwidth, strheight) {
    switch (Currenttype) {
        case "xheditor":
            $("#" + currentControlID).xheditor(false);
            //EditorInstance.remove();
            break;
        case "news_editor":
        case "ckeditor":
            if (EditorInstance) {
                EditorInstance.destroy();
                EditorInstance = null;
            }
            break;
        case "html_editor":
            if (CodeMirroreditor) {
                $("#" + currentControlID).val(CodeMirroreditor.getValue());
                CodeMirroreditor.toTextArea();
            }
            //editAreaLoader.delete_instance(currentControlID);
    }
    Currenttype = $("#EditorSelect").val();
    InitEditor(currentControlID, Currenttype, strwidth, strheight, false);
}
//当前编辑器上添加基本控制元素
function InsertBaseControl(currentControlID, type, strwidth, strheight) {
    Currenttype = type;
    //当前的操作Panel
    var ParentControl = $("#" + currentControlID).parent();
    //新建div
    var BaseControlDiv = $("<div id=\"BaseControl\"></div>").css("margin-top", "3px").css("margin-bottom", "3px");

    //****切换编辑器
    $("<span style=\"color:Red;font-weight: bold;font-size: 13px;\">编辑器选择：</span>").css("margin-left", "5px").appendTo(BaseControlDiv);
    var EditorSelect = $("<select name='EditorSelect' id='EditorSelect'></select>").css("margin-left", "5px").bind("change", function () {
        ReInstall(currentControlID, strwidth, strheight);
    });
    EditorSelect.append("<option value='ckeditor'>ckeditor</option>");
    EditorSelect.append("<option value='xheditor'>xheditor</option>");
    EditorSelect.append("<option value='html_editor'>html_editor</option>");
    EditorSelect.val(type);
    EditorSelect.appendTo(BaseControlDiv);

    //****快捷操作按钮
    $("<span style=\"color:Red;font-weight: bold;font-size: 13px;\">快捷操作：</span>").css("margin-left", "5px").appendTo(BaseControlDiv);
    //粘贴控件
    /*
    var PasteInput = $('<input class="button_style" title="粘贴进来" name="PastToControl"  value="粘贴进来"  type="button" />').bind("click", function () {
        PasteForEditor();
    }).css("margin-left", "1px");
    PasteInput.appendTo(BaseControlDiv);
    */
    //格式化
    var FormatInput = $('<input class="button_style" title="将HTML标签全部转换成P标签" name="AdvanceFormatTextControl"  value="格式化"  type="button" />').bind("click", function () {
        switchFormat(currentControlID);
        return false;
    }).css("margin-left", "10px");
    FormatInput.appendTo(BaseControlDiv);
    //图片自动分页
    var PicAutoPageInput = $('<input class="button_style" title="图片自动分页" name="PageAutoPageControl" id="PageAutoPageControl"  value="图片分页"  type="button" />').bind("click", function () {
        PageAutoPage(currentControlID);
        return false;
    }).css("margin-left", "10px");
    PicAutoPageInput.appendTo(BaseControlDiv);
    //简繁转换
    var Simple2TraditionalInput = $('<input class="button_style" title="简繁转换" name="S2TControl" id="S2TControl" value="简->繁"  type="button" />').bind("click", function () {
        return SimpleAndTradiation(currentControlID); //ChangeSimplifie2TraditionalFont($('#' + currentControlID).val(), 'S2TControl', currentControlID);
    }).css("margin-left", "10px");
    Simple2TraditionalInput.appendTo(BaseControlDiv);

    //****图片选项
    $("<span style=\"color:Red;font-weight: bold;font-size: 13px;\">图片选项：</span>").css("margin-left", "5px").appendTo(BaseControlDiv);
    //长宽
    BaseControlDiv.append("<span style=\"font-weight: bold;font-size: 12px;\">长宽限制 </span>");
    $('<input name="txtWidth"  id="txtWidth"  type="text"  style=" width:40px;"   value="600"  />').appendTo(BaseControlDiv);
    $("<span style=\"font-weight: bold;font-size: 12px;\">×</span>").appendTo(BaseControlDiv);
    $('<input name="txtHeight" id="txtHeight" type="text"  style=" width:40px;"   value="0"  />').appendTo(BaseControlDiv);
    //图片等比压缩
    $('<input name="chkPicResize" id="chkPicResize" type="checkbox"  checked="checked"  value="true"  />').css("margin-left", "10px").appendTo(BaseControlDiv);
    BaseControlDiv.append("<span style=\"font-weight: bold;font-size: 12px;\">等比缩放</span>");


    //图片本地化
    var PicLocalInput = $('<input name="chkPicLocating" id="chkPicLocating" type="checkbox"  checked="checked"  value="true"  />').css("margin-left", "10px");
    PicLocalInput.appendTo(BaseControlDiv);
    BaseControlDiv.append("<span style=\"font-weight: bold;font-size: 12px;\">图片本地化</span>");
    //图片水印选项
    BaseControlDiv.append("<span style=\"font-weight: bold;font-size: 12px;margin-left:10px;\">图片水印:</span>");
    var PicWaterLocation = $("<select name='chkPicWaterSelect' id='chkPicWaterSelect'><option value='0'>不加水印</option><option value='1'>左上角</option><option value='2'>右上角</option><option value='3'>左下角</option><option value='4' selected>右下角</option><option value='5'>居中偏下</option></select>").css("margin-left", "12px");
    PicWaterLocation.appendTo(BaseControlDiv);

    BaseControlDiv.prependTo(ParentControl); //将新建的基本控制附加到当前的操作窗体内
}